/**
 * 用户分析增加
 * sherlock
 * 2016年7月11日15:27:13
 */

define( [
  'require',
  'jquery',
  'api',
  'bigwe_utils',
  'message',
  'dad',
  './utils',
  'imgChoose',
  'mpnewsChoose',
  'videoUploader',
  'videoChoose'
], function( require, $ ) {
  var utils = require( './utils' );
  var ic = require( 'imgChoose' );
  var vu = require( 'videoUploader' );
  var vc = require( 'videoChoose' );
  var bu = require( 'bigwe_utils' );
  var mpc = require( 'mpnewsChoose' );
  var BIGWE_API = require( 'api' );
  var ShowTitleMessage = require( 'message' );

  var htmlBuild = utils.htmlBuild;

  var returnParam = {};
  var thisAPI = BIGWE_API.CUSTOM_MENU;
  var showTime = ShowTitleMessage.showTime;
  var appid;
  var verify_info;
  // 取得appid
  returnParam.init = function( data ) {
    data = data || {};
    appid = data.app_id;
    verify_info = data.verify_type_info;
  }


  $( '#menu_manage .mobile_hd' ).text( $( '.mail_modal .list-sub-text>.mail-name' ).text() || '' );
  // 当前编辑父菜单
  var curIndex = -1,
    // 当前编辑子菜单
    curIndexChild = -1;

  var clickLoad = 0;

  var menuWidthClass = 'menu_num1 menu_num2 menu_num3 menu_num4';

  var mediaContext = $( '#editDiv' );;
  ( function() {
    var html = $( $.trim( $( '#mediaset' ).html() ) );
    if ( verify_info * 1 != -1 ) {
      $( '.js_textSetting', html ).removeClass( 'hide' );
    }

    $( '.js_mediaHtml' ).html( html );
    $( '.js_textSetting', '#auto_reply' ).removeClass( 'hide' );
  }() );

  var customOption = {

    data: {
      'menu': {
        'button': []
      }
    },
    getData: function() {
      return this.data.menu.button;
    },
    setData: function( data ) {
      return this.data.menu.button = data;
    },
    setAttrbute: function( key, value ) {

      if ( typeof key === 'object' ) {

        key.is_edit = 1;

        if ( curIndexChild > -1 ) {
          $.extend( this.getData()[ curIndex ].sub_button[ curIndexChild ], key );
        } else {
          $.extend( this.getData()[ curIndex ], key );
        }
      } else {

        if ( curIndexChild > -1 ) {
          var targetObj = this.getData()[ curIndex ].sub_button[ curIndexChild ];
          targetObj[ key ] = value;
          targetObj.is_edit = 1;

        } else {
          this.getData()[ curIndex ][ key ] = value;
          this.getData()[ curIndex ].is_edit = 1;
        }
      }

      return this;
    },
    mpnewsData: function( data ) {
      return {
        'article_group': data.group,
        'content_url': data.id ? '/_article?p=' + data.id : '',
        'cover_url': data.image,
        'digest': data.summary,
        'title': data.title
      }
    },
    cutString: function( pStr, pLen ) {

      // 原字符串长度  
      var _strLen = pStr.length;

      var _tmpCode;

      var _cutString;

      // 默认情况下，返回的字符串是原字符串的一部分  
      var _cutFlag = "1";

      var _lenCount = 0;

      var _ret = false;

      function isFull( pChar ) {
        if ( ( pChar.charCodeAt( 0 ) > 128 ) ) {
          return true;
        } else {
          return false;
        }
      }

      // 原字符串长度  
      var _strLen = pStr.length;

      var _tmpCode;

      var _cutString;

      // 默认情况下，返回的字符串是原字符串的一部分  
      var _cutFlag = "1";

      var _lenCount = 0;

      var _ret = false;

      if ( _strLen <= pLen / 2 ) {
        _cutString = pStr;
        _ret = true;
      }

      if ( !_ret ) {
        for ( var i = 0; i < _strLen; i++ ) {
          if ( isFull( pStr.charAt( i ) ) ) {
            _lenCount += 2;
          } else {
            _lenCount += 1;
          }

          if ( _lenCount > pLen ) {
            _cutString = pStr.substring( 0, i );
            _ret = true;
            break;
          } else if ( _lenCount == pLen ) {
            _cutString = pStr.substring( 0, i + 1 );
            _ret = true;
            break;
          }
        }
      }

      if ( !_ret ) {
        _cutString = pStr;
        _ret = true;
      }

      if ( _cutString.length == _strLen ) {
        _cutFlag = "0";
      }

      return {
        "cutstring": _cutString,
        "cutflag": _cutFlag
      };
    },
    isSetContent: function( data ) {
      if ( data.type === 'news' ) {
        return data.news_info;
      } else if ( data.type === 'text' || data.type === 'video' ) {
        return data.value;
      } else if ( data.type === 'img' || data.type === 'view' ) {
        return data.url;
      } else {
        return 0;
      }
    }
  };
  var menuType = {
    'news': 0,
    'text': 1,
    'img': 2,
    'radio': 3,
    'video': 4,
    'view': 5
  }
  returnParam.customMenuObjChange = function( param ) {
    param = param || {};
    $( '#menu_manage .mobile_hd' ).text( param.user_name || '' );
    appid = param.app_id;
    if ( $( '#sort_finish' ).css( 'display' ) != 'none' ) {
      $( '#sort_finish' ).trigger( 'click' );
    }
    menuAjaxDataRequest( param.app_id, function( data ) {

    } );
  }

  function customMenuMaterialCallback() {

    mpc.mpnewsChooseCallback = function( param ) {
      var mpnews = param.mpnewsArray,
        newMpnews = [];
      var mpnewsData = new Object();
      for ( i in mpnews.articles ) {
        newMpnews.push( htmlBuild.mpnewsData( mpnews.articles[ i ], mpnews.article_group ) );
      }
      customOption.setAttrbute( {
        type: 'news',
        news_info: mpnewsData.news_info = newMpnews,
        article_group: ( mpnews.article_group || '' )
      } );
      conentAppend[ 0 ]( mpnewsData );
    }
    ic.imagesChooseCallback = function( callbackParam ) {

      customOption.setAttrbute( {
        type: 'img',
        url: callbackParam
      } );
      conentAppend[ 2 ]( {
        'url': callbackParam
      } );
    }

    vc.videoChooseCallback = function( callbackParam ) {
      var video = callbackParam.videoObj;
      var param = {
        type: 'video',
        video_id: video.video_id,
        value: video.address,
        video_title: video.title,
        video_summary: video.synopsis
      }

      customOption.setAttrbute( param );
      conentAppend[ 4 ]( param );
    }

    /*
     *2016年8月8日16:00:48，上传视频 确定 sherlockl
     */
    vu.doSave = function( htm, data ) {

      var param = {
        type: 'video',
        video_id: data.video_id,
        value: data.address,
        video_title: data.title,
        video_summary: data.synopsis,
      };

      customOption.setAttrbute( param );

      conentAppend[ 4 ]( param );
    }

    /*
     *2016年8月8日16:00:48，上传图片 确定 sherlockl
     */
    utils.imgOnSave = function( data ) {
      customOption.setAttrbute( {
        type: 'img',
        url: data.image
      } );
      conentAppend[ 2 ]( {
        'url': data.image
      } );
    }
  }

  function menuAjaxDataRequest( appid, fn ) {

    var menuList = $( '#menuList' );

    curIndex = -1;
    curIndexChild = -1;
    $( '#js_none' ).show();
    $( '#js_rightBox' ).hide();

    $( '.jsMsgSendTab', '#menu_manage' ).show()
    $( '.wait_content', '#menu_manage' ).empty().hide();

    function noDataOrNoAuth() {
      menuList.addClass( 'menu_num1' ).find( '>.add_menu_js' ).show();
      customOption.setData( [] );
      $( '#custom_menu_save' ).addClass( 'disabled' ).prop( 'disabled' );
      $( '#custom_menu_publish' ).addClass( 'disabled' ).prop( 'disabled' );
    }
    $( '#wrap_mask' ).fadeIn();
    $.ajax( {
      type: 'POST',
      url: thisAPI.GET_MENU,
      data: {
        app_id: appid
      },
      success: function( data ) {
        var menuList = $( '#menuList' );
        if ( data && typeof data != 'object' ) {
          data = $.parseJSON( data );
        }

        if ( data.data.show_menu == '0' ) {
          $( '.menu_form_area,.edit_menu > button,.sort_btn_wrp' ).addClass( 'hide' );
          $( '.mobile_backdrop' ).removeClass( 'hide' ).addClass( 'in' );
          $( '.enable_menu' ).removeClass( 'hide' );
        }

        menuList.removeClass( menuWidthClass ).find( '>.menu_item' ).remove();
        if ( !data.ret && data.data ) {
          var dataLen = data.data.menu.button.length;
          if ( dataLen > 3 ) {
            ShowTitleMessage.showWarning( '数据异常', showTime );
            menuList.addClass( 'menu_num1' );
            return;
          }
          if ( data.data.verify_info * 1 != -1 ) {
            $( '#redirect' ).removeAttr( 'disabled' ).parent().removeClass( 'hide' );
            $( '.js_textSetting', '#menu_manage' ).removeClass( 'hide' );
          } else {
            $( '#redirect' ).prop( 'disabled', 'disabled' ).parent().addClass( 'hide' );
            $( '.js_textSetting', '#menu_manage' ).addClass( 'hide' );
          }

          customOption.data = data.data;
          data = data.data.menu.button;
          if ( data && data.length ) {
            $( '#custom_menu_save' ).removeClass( 'disabled' ).removeAttr( 'disabled' );
            $( '#custom_menu_publish' ).removeClass( 'disabled' ).removeAttr( 'disabled' );

            $( '.add_menu_js', menuList ).show();
            menuList.addClass( 'menu_num' + ( data.length + 1 ) );
            if ( data.length > 2 ) {
              $( '.add_menu_js', menuList ).hide();
            } else if ( data.length > 1 ) {
              //$('#menu_sort').removeAttr('disabled');
            }
            for ( key in data ) {
              var parentData = data[ key ];
              var parentMenu = $( getParentMenuHtml() );

              parentMenu.attr( 'menu-type', parentData.type )
              $( '.parent_menu_name', parentMenu ).text( parentData.name );

              if ( parentData.sub_button && parentData.sub_button.length ) {

                $( '.js_hasChild', parentMenu ).show();
                if ( parentData.sub_button.length >= 5 ) {
                  $( '.js_doAddMenuBox', parentMenu ).hide();
                }
                for ( i in parentData.sub_button ) {
                  var childData = parentData.sub_button[ i ];
                  var childMenu = $( getChildMenuHtml() );

                  childMenu.attr( 'child-menu-type', childData.type );
                  $( '.child_menuName', childMenu ).text( childData.name || '' );
                  $( '.sub_pre_menu_list .js_doAddMenuBox', parentMenu ).before( childMenu );
                }
              }
              $( '.add_menu_js', menuList ).before( parentMenu );
            }

          } else {
            noDataOrNoAuth();
          }
          if ( fn ) fn( data.data );
        } else {
          ShowTitleMessage.showWarning( data.msg || 'ERROR_CODE:' + data.ret, showTime );
          noDataOrNoAuth();
          return;
        }
      },
      complete: function() {
        $( '#wrap_mask' ).fadeOut();
      },
      error: function() {

      }
    } );

  }

  var deleteHtml = '<a href="javascript: void(0);" class="del_content">删除</a>';
  // 放置内容
  var conentAppend = [
    // 图文放置
    function( data ) {
      var tabContent = $( '.tab_panel .tab_content', mediaContext ).eq( 0 );
      if ( data.news_info && data.news_info.length ) {
        $( '.tab_cont_cover', tabContent ).hide();
        $( '.wait_content', tabContent ).html( htmlBuild.getGraphHtml( data.news_info ) ).append( deleteHtml ).show();
      }

    },
    // 文字放置
    function( data ) {
      $( '.js_editorArea', mediaContext ).text( data.value ).trigger( 'keyup' );
    },
    // 图片放置
    function( data ) {

      var tabContent = $( '.tab_panel .tab_content', mediaContext ).eq( 2 );
      $( '.tab_cont_cover', tabContent ).hide();
      $( '.wait_content', tabContent ).html( htmlBuild.getImgHtml( data.url ) ).append( deleteHtml ).show();

    },
    // 语音放置
    function() {},
    // 视频放置
    function( data ) {
      var tabContent = $( '.tab_panel .tab_content', mediaContext ).eq( 4 );
      $( '.tab_cont_cover', tabContent ).hide();
      $( '.wait_content', tabContent ).html( htmlBuild.getVideoHtml( data ) ).append( deleteHtml ).show();
    },
    // 跳转网页
    function( data ) {

      $( '#urlText' ).val( data.url );

    }
  ]

  // 删除当前设定的内容
  $( '#menu_manage' ).on( 'click', '.wait_content .del_content', function() {

    $( this ).parent().hide().empty().prev().show();

  } );
  // 子菜单选择
  $( '#menuList' ).on( 'click', '.sub_pre_menu_list .js_addMenuBox', function( e ) {
    e.stopPropagation();

    $( '.menu_item', '#menuList' ).removeClass( 'selected' );
    $( this ).addClass( 'child_selected' ).siblings().removeClass( 'child_selected' );


    // ---------------about data
    $( '#js_innerNone' ).hide();
    $( '#js_none' ).hide();
    $( '#menu_content_radio' ).show();
    $( '.menu_content_container' ).show();
    $( '#js_rightBox' ).show();
    $( '.js_menu_text' ).text( '子菜单' );
    $( '.js_titleNolTips' ).text( '字数不超过8个汉字或16个字母' );


    var parentIndex = curIndex = $( this ).parents( '.pre_menu_item' ).index();
    var thisIndex = curIndexChild = $( this ).index();
    var thisData = customOption.getData()[ parentIndex ].sub_button[ thisIndex ];
    $( '#menu_name' ).val( thisData.name || '子菜单名称' );
    $( '.js_menu' ).text( thisData.name || $( '.js_menuTitle' ).text() );
    menuEvent( thisData );

  } );
  // 菜单点击事件
  function menuEvent( data ) {

    var typeIndex = menuType[ data.type ] || 0;
    removeCheckError();
    if ( typeIndex != 5 ) {
      $( '.js_radio_sendMsg' ).trigger( 'click' );
      $( '.js_tab_navs .tab_nav', mediaContext ).eq( typeIndex ).trigger( 'click' );
    } else {
      $( '.js_radio_url' ).trigger( 'click' );
    }

    emptyContent();
    try {
      conentAppend[ typeIndex ]( data );
    } catch ( e ) {
      alert( '---------------------------------------\n产生了错误的数据，请与管理员联系\n---------------------------------------' )
    }
  }
  $( '.js_errorRemove' ).click( removeCheckError );

  function removeCheckError() {

    $( '#editDiv' ).removeClass( 'error' );
    $( '#js_errTips' ).hide();
  }
  // 清空界面已设置的内容
  function emptyContent() {

    $( '.tab_content .tab_cont_cover', mediaContext ).show();
    $( '.tab_content .wait_content', mediaContext ).empty().hide();
    $( '.js_editorArea', mediaContext ).text( '' ).trigger( 'keyup' );
    $( '#urlText', mediaContext ).val( '' );

    return $( '#js_rightBox' );

  }

  // 父菜单选择
  $( '#menuList' ).on( 'click', '.js_itemchange', function() {

    $( this ).addClass( 'selected child_show' ).siblings().removeClass( 'selected child_show' );
    $( '#menuList .sub_pre_menu_list .js_addMenuBox' ).removeClass( 'child_selected' );

    // ----------------about data
    $( '#js_none' ).hide();
    $( '#js_rightBox' ).show();
    var thisIndex = curIndex = $( this ).index();
    curIndexChild = -1;
    var thisData = customOption.getData()[ thisIndex ];
    if ( thisData.sub_button ) {
      $( '#js_innerNone' ).show();
      $( '#menu_content_radio' ).hide();
      $( '.menu_content_container' ).hide();
    } else {
      $( '#js_innerNone' ).hide();
      $( '#menu_content_radio' ).show();
      $( '.menu_content_container' ).show();

      menuEvent( thisData );
    }
    $( '.js_menu_text' ).text( '菜单' );
    $( '.js_titleNolTips' ).text( '字数不超过4个汉字或8个字母' );

    $( '#menu_name' ).val( thisData.name || '菜单名称' );
    $( '.js_menu' ).text( thisData.name || $( '.js_menuTitle' ).text() );
  } );
  //--------------------------------编辑数据  start
  // 编辑菜单的名称
  $( '#menu_name' ).on( {
    change: function() {

      var thisVal = $( this ).val();
      if ( /^\s*$/.test( thisVal ) ) {
        thisVal = curIndexChild > -1 ? '子菜单名称' : '菜单名称';
        $( '.js_titlenoTips' ).text( '请输入' + thisVal ).show();
      } else {
        $( '.js_titlenoTips' ).hide();
      }
      customOption.setAttrbute( 'name', thisVal );
      $( '.js_menu' ).text( thisVal || $( '.js_menuTitle' ).text() );

      if ( curIndexChild > -1 ) {
        $( '#menuList .pre_menu_item' )
          .eq( curIndex )
          .find( '.sub_pre_menu_list .childMenu_item' )
          .eq( curIndexChild )
          .find( '.child_menuName' )
          .text( thisVal );

      } else {
        $( '#menuList .pre_menu_item' )
          .eq( curIndex )
          .find( '.parent_menu_name' )
          .text( thisVal );
      }

    },
    keyup: function() {
      var textLen = strlen( $( this ).val() );
      var maxLen = curIndexChild > -1 ? 16 : 8;
      if ( textLen > maxLen ) {
        $( '.js_titleEorTips' ).show();
      } else {
        $( '.js_titleEorTips' ).hide();
      }
    },
    blur: function() {
      var maxLen = curIndexChild > -1 ? 16 : 8;
      $( this ).val( customOption.cutString( $( this ).val(), maxLen ).cutstring ).trigger( 'change' ).trigger( 'keyup' );
    }
  } );

  // 跳转网页地址
  $( '#urlText' ).on( {
    change: function() {
      var thisVal = $.trim( $( this ).val() );

      if ( !thisVal ) {
        return;
      }

      if ( !$.isUrlCheck( thisVal ) ) {
        ShowTitleMessage.showWarning( '请输入正确的URL', showTime );
        return;
      }

      if ( thisVal ) {
        customOption.setAttrbute( {
          'type': 'view',
          'url': thisVal
        } );
      } else {
        customOption.setAttrbute( {
          'type': 'news',
          'url': ''
        } );
      }
    },
    focus: function() {
      $( '#js_errTips' ).hide();
    }
  } );


  // 输入文字消息
  $( '.js_editorArea' ).on( {
    focus: function() {

    },
    keyup: function() {
      maxLen = $( this ).attr( 'maxlength' ) || 600;
      var thisText = $( this ).text() || $( this ).val();
      if ( thisText.length <= maxLen ) {
        $( '.editor_toolbar .editor_tip', $( this ).parent() ).html( '还可以输入' + ( maxLen - thisText.length ) + '字' );
      } else {
        $( '.editor_toolbar .editor_tip', $( this ).parent() ).html( '已超出<span style="color: #e15f63">' + ( thisText.length - maxLen ) + '</span>字' );
      }
    },
    paste: function() {
      $( this ).text( $( this ).text() );
    }
  } );

  $( '.js_editorArea', mediaContext ).on( {
    change: textChange,
    blur: textChange
  } );

  function textChange() {
    var thisText = $( this ).text(),
      maxLen = $( this ).attr( 'maxlength' ) || 600;
    //if (!/^\s*$/.test(thisText)) {}
    if ( thisText.length > maxLen ) return;
    customOption.setAttrbute( {
      type: 'text',
      value: thisText
    } );
  }

  // 删除确认
  $( '#deleteSave' ).on( 'click', function() {

    function nodeRemove() {
      var currentObj = $( '#menuList .pre_menu_item' ).eq( curIndex );
      currentObj.removeClass( 'child_show' )
      // 子菜单
      if ( curIndexChild > -1 ) {

        customOption.getData()[ curIndex ].sub_button.splice( curIndexChild, 1 );



        currentObj.find( '.sub_pre_menu_list .childMenu_item' )
          .eq( curIndexChild )
          .remove();
        if ( !currentObj.find( '.sub_pre_menu_list .childMenu_item' ).length ) {
          currentObj.removeClass( 'haschild_menu' );
        }
        currentObj.find( '.js_doAddMenuBox' ).show();
        if ( !customOption.getData()[ curIndex ].sub_button.length ) {
          customOption.getData()[ curIndex ].sub_button = null;
        }

      } else {

        customOption.getData().splice( curIndex, 1 );

        $( '#menuList .pre_menu_item' )
          .eq( curIndex )
          .remove();

        if ( !customOption.getData().length ) {
          $( '#custom_menu_save' ).addClass( 'disabled' ).prop( 'disabled' );
          $( '#custom_menu_publish' ).addClass( 'disabled' ).prop( 'disabled' );
        }
        $( '#menuList' ).removeClass( menuWidthClass ).addClass( 'menu_num' + $( '#menuList .pre_menu_item' ).length );

      }

      // 重置当前编辑对象
      curIndex = -1;
      curIndexChild = -1;

      var menuLen = $( '#menuList .pre_menu_item' ).length;
      $( '#menuList' ).removeClass( 'menu_num1 menu_num2 menu_num3' ).addClass( 'menu_num' + ( menuLen || 1 ) );
      if ( menuLen < 4 ) {
        $( '#menuList .add_menu_css' ).show();
      }
      if ( menuLen < 3 ) {
        //$('#menu_sort').prop('disabled', 'disabled');
      }

      emptyContent().hide();
      $( '#js_none' ).show();
    }

    var menuId = curIndexChild > -1 ? customOption.getData()[ curIndex ].sub_button[ curIndexChild ].id : customOption.getData()[ curIndex ].id;

    $( '#deleteConfirm' ).modal( 'hide' );

    if ( !menuId ) {
      nodeRemove();
      return;
    }
    $.ajax( {
      type: 'post',
      url: thisAPI.DEL_MENU,
      data: {
        id: menuId
      },
      success: function( data ) {
        data = typeof data === 'string' ? $.parseJSON( data ) : data;
        if ( data.ret ) {
          ShowTitleMessage.showWarning( data.msg || '删除失败', showTime );
          return;
        }
        nodeRemove();
      }
    } );


  } );

  function saveSuccess() {

    for ( i in customOption.getData() ) {
      var parentMenu = customOption.getData()[ i ];
      parentMenu.is_edit = 0;
      for ( j in parentMenu.sub_button ) {
        parentMenu.sub_button[ j ].is_edit = 0;
      }
    }
  }
  // 保存操作
  $( '#custom_menu_save' ).click( function() {
    if ( !customOption.getData().length ) return;
    var me = this;
    $( me ).prop( 'disabled', 'disabled' );
    $( '#wrap_mask' ).fadeIn();
    $.ajax( {
      type: 'post',
      url: thisAPI.SAVE_MENU,
      data: {
        'sub_data': JSON.stringify( customOption.data )
      },
      success: function( data ) {
        data = typeof data === 'Object' ? data : $.parseJSON( data );
        if ( data.ret ) {
          ShowTitleMessage.showWarning( data.msg || '保存出现错误', showTime );
        } else {
          ShowTitleMessage.show( '保存成功', showTime );
          if ( data.data ) {
            customOption.setData( data.data.menu.button );
          }
          saveSuccess();
        }
      },
      complete: function() {
        $( me ).removeAttr( 'disabled' );
        $( '#wrap_mask' ).fadeOut();
      }
    } );
  } );

  // 保存并发布操作
  $( '#custom_menu_publish,.enable_btn' ).click( function() {
    if ( $( this ).hasClass( 'enable_btn' ) ) {
      $( '#publishConfirm' ).find( '.enable_prompt' ).removeClass( 'hide' ).siblings( '.publish_prompt' ).addClass( 'hide' );
      $( '#publishSure' ).attr( 'data-btn', 'enable' );
    } else {
      $( '#publishConfirm' ).find( '.enable_prompt' ).addClass( 'hide' ).siblings( '.publish_prompt' ).removeClass( 'hide' );
      $( '#publishSure' ).removeAttr( 'data-btn' );
    }
    if ( !customOption.getData().length ) return;
    var validateMenu = customOption.getData();

    var loopFlag = !0;
    var trigerFlag = !0;

    function checkError() {
      $( '#editDiv' ).addClass( 'error' );
      $( '#js_errTips' ).text( '请设置当前菜单内容' ).show();
    }

    if ( $( '#redirect' )[ 0 ].checked ) {
      var urlText = $.trim( $( '#urlText' ).val() );
      if ( !urlText ) {
        $( '#js_errTips' ).text( '请输入页面地址' ).show();
        return;
      }
      if ( !$.isUrlCheck( urlText ) ) {
        ShowTitleMessage.showWarning( '请输入正确的URL', showTime );
        return;
      }
    } else {
      if ( $( '.js_tab_navs .tab_text' ).hasClass( 'selected' ) && $( '.js_editorArea' ).text().length > 600 ) {
        $( '#js_errTips' ).text( '文字必须为1到600个字' ).show();
        return;
      }
    }

    for ( i in validateMenu ) {
      if ( loopFlag ) {
        if ( validateMenu[ i ].sub_button ) {
          var subButton = validateMenu[ i ].sub_button;
          for ( y in subButton ) {
            if ( loopFlag ) {
              var childBtn = subButton[ y ];
              loopFlag = customOption.isSetContent( childBtn );
              if ( !loopFlag ) {
                trigerFlag = 0;
                $( '#menuList .menu_item' ).eq( i ).trigger( 'click' ).find( '.sub_pre_menu_list .childMenu_item' ).eq( y ).trigger( 'click' );
                checkError();
              }
            } else {
              break;
            }
          }
        } else {
          loopFlag = customOption.isSetContent( validateMenu[ i ] );
          if ( trigerFlag ) {
            if ( !loopFlag ) {
              $( '#menuList .menu_item' ).eq( i ).trigger( 'click' );
              checkError();
            }
          }
        }
      } else {
        break;
      }
    }
    if ( !loopFlag ) return;

    $( '#publishConfirm' ).modal( 'show' );

  } );
  // 发布确认
  $( '#publishSure' ).click( function() {
    var me = $( this );
    me.prop( 'disabled', 'disabled' );
    $( '#wrap_mask' ).fadeIn();
    me.parents( '#publishConfirm' ).modal( 'hide' );
    $.ajax( {
      type: 'post',
      url: thisAPI.SYNCH_MENU,
      timeout: 6e5,
      data: {
        'sub_data': JSON.stringify( customOption.data ),
        'app_id': appid
      },
      success: function( data ) {
        data = typeof data === 'Object' ? data : $.parseJSON( data );
        if ( data.ret ) {
          ShowTitleMessage.showWarning( '同步失败，请稍后重试', showTime );
        } else {
          if ( $( '#publishSure' ).data( 'btn' ) ) {
            $( '.menu_form_area,.edit_menu > button,.sort_btn_wrp' ).removeClass( 'hide' );
            $( '.mobile_backdrop' ).addClass( 'hide' ).removeClass( 'in' );
            $( '.enable_menu' ).addClass( 'hide' );
          }
          ShowTitleMessage.show( '同步成功！', showTime );
          saveSuccess();
          if ( data.data ) {
            customOption.setData( data.data.menu.button );
          }
        }
      },
      error: function( xhr ) {
        if ( xhr.status == 404 ) {
          ShowTitleMessage.showWarning( '接口出现错误', showTime );
        }
      },
      complete: function() {
        me.removeAttr( 'disabled' );
        $( '#wrap_mask' ).fadeOut();
      }
    } );
  } );
  //--------------------------------编辑数据  end

  // 创建一个菜单数据对象
  function createMenu( option ) {
    option = option || {};

    return {
      id: '',
      url: '',
      key: '',
      type: '',
      sort: option.sort,
      name: ( option.menuName || '' ),
      value: '',
      status: '',
      app_id: appid,
      content: '',
      media_id: '',
      parent_id: ( option.parent_id || '' ),
      news_info: null,
      sub_button: null,
      is_menu_open: '',
      article_group: ''
    }
  }

  $( '#jsDelBt' ).on( 'click', function() {

    $( '.deletemenu_confirm', '#deleteConfirm' ).show();
    $( '.add_childConfirm', '#deleteConfirm' ).hide();
    $( '#menuNameText' ).text( $( '#menu_name' ).val() || '菜单名称' ).parents( '#deleteConfirm' ).modal( 'show' );

  } );

  // 菜单排序
  $( '#menu_sort' ).click( function() {

    var menuItem = $( '.menu_item', '#menuList' );

    menuItem.each( function() {

      if ( !$( '.childMenu_item', this ).length ) {
        $( '.sub_pre_menu_box', this ).hide();
      }

    } );

    $( '.childMenu_item', '#menuList' ).removeClass( 'child_selected js_addMenuBox' );
    menuItem.addClass( 'child_show' )
      .removeClass( 'selected js_itemchange' );

    $( this ).hide();
    $( '#sort_finish' ).show();
    $( '#menuList' ).addClass( 'sorting' );
    var placeholder = '释放';
    window.parentMenu = $( '#menuList' ).dad( {
      target: '.menu_item',
      containerClass: 'dad-container1',
      placeholder: placeholder,
      callback: menuSort
    } );

    window.childMenu = $( '.sub_pre_menu_list', '#menuList' ).dad( {
      target: '.childMenu_item',
      containerClass: 'dad-container2',
      placeholder: placeholder,
      callback: menuSort
    } );
    var menuLen = $( '#menuList .pre_menu_item ' ).length;
    $( '#menuList' ).removeClass( menuWidthClass ).addClass( 'menu_num' + ( menuLen - 1 ) );

    $( '#js_rightBox' ).hide();
    $( '#js_none' ).text( '请通过拖拽左边的菜单进行排序' ).show();
  } );

  function menuSort( parama ) {
    var me = $( this );
    var newArray = new Array();
    if ( parama.hasClass( 'pre_menu_item' ) ) {
      var sort = 0;
      $( '.menu_item', this ).each( function() {
        var dataOldIndex = $( this ).attr( 'data-dad-id' ) * 1 - 1;
        var dataObj = customOption.getData()[ dataOldIndex ];
        dataObj.sort = sort;
        // 标记已被编辑过
        dataObj.is_edit = 1;
        newArray.push( dataObj );
        sort++;
      } ).each( function( index ) {
        $( this ).attr( 'data-dad-id', index + 1 );
      } );

      customOption.setData( newArray );
    } else {
      var parentIndex = me.parent().parent().index();
      var sort = 0;
      $( '.childMenu_item', this ).each( function() {
        var dataOldIndex = $( this ).attr( 'data-dad-id' ) * 1 - 1;
        var dataObj = customOption.getData()[ parentIndex ].sub_button[ dataOldIndex ];
        dataObj.sort = sort;
        // 标记已被编辑过
        dataObj.is_edit = 1;
        newArray.push( dataObj );
        sort++;
      } ).each( function( index ) {
        $( this ).attr( 'data-dad-id', index + 1 );
      } );

      customOption.getData()[ parentIndex ].sub_button = newArray;
    }

  }

  // 菜单排序完成
  $( '#sort_finish' ).click( function() {
    $( this ).hide();
    $( '#menu_sort' ).fadeIn();
    $( '#menuList' ).removeClass( 'sorting' );
    $( '.childMenu_item', '#menuList' ).addClass( 'js_addMenuBox' );
    $( '.menu_item', '#menuList' )
      .removeClass( 'child_show' )
      .addClass( 'js_itemchange' )
      .find( '.sub_pre_menu_box' )
      .show();
    if ( window.parentMenu.length ) {
      window.parentMenu.deactivate();
    }
    if ( window.childMenu.length ) {
      window.childMenu.deactivate();
    }


    var menuLen = $( '#menuList .pre_menu_item ' ).length;
    $( '#menuList' ).removeClass( menuWidthClass ).addClass( 'menu_num' + ( menuLen ) );

    //$('#js_rightBox').fadeIn();
    $( '#js_none' ).text( '点击左侧菜单进行编辑操作' );
  } );

  // 父菜单添加
  $( '#menuList' ).on( 'click', '.add_menu_js', function() {

    $( '#custom_menu_save' ).removeClass( 'disabled' ).removeAttr( 'disabled' );
    $( '#custom_menu_publish' ).removeClass( 'disabled' ).removeAttr( 'disabled' );

    var parentMenuList = $( '#menuList .menu_item' );
    if ( parentMenuList.length >= 3 ) return;

    customOption.getData().push( createMenu( {
      'sort': parentMenuList.length,
      'menuName': '菜单名称'
    } ) );

    var addObj = $( getParentMenuHtml() ) //.addClass('selected child_show');
    parentMenuList.removeClass( 'selected child_show' );
    $( this ).before( addObj );
    addObj.trigger( 'click' );
    var afterAddLen = $( '#menuList .pre_menu_item' ).length;

    var thisParent = $( this ).parent().removeClass( menuWidthClass ).addClass( 'menu_num' + afterAddLen );

    if ( afterAddLen == 3 ) {
      thisParent.addClass( 'menu_num3' );
      //$('#menu_sort').removeAttr('disabled');
    } else if ( afterAddLen == 4 ) {
      $( this ).hide();
    }

  } );

  // 子菜单添加
  $( '#menuList' ).on( 'click', '.sub_pre_menu_list .js_doAddMenuBox', function( e ) {

    e.stopPropagation();
    $( '.menu_item', '#menuList' ).removeClass( 'selected' );
    $( this ).siblings().removeClass( 'child_selected' );
    var childMenuList = $( this ).parent();
    var childMenuLength = $( '.js_addMenuBox', childMenuList ).length;
    if ( childMenuLength > 5 ) return;
    var parentData = customOption.getData()[ curIndex ];
    if ( customOption.isSetContent( parentData ) ) {
      $( '#addChildConfirm' ).modal( 'show' ).data( 'menuEvent', this );
      return;
    }

    doAddChildMenu.call( this );

  } );

  // 子菜单添加
  function doAddChildMenu() {
    if ( !customOption.getData()[ curIndex ].sub_button ) {
      customOption.getData()[ curIndex ].sub_button = [];
    }
    var childMenu = createMenu( {
      'sort': customOption.getData()[ curIndex ].sub_button.length,
      'parent_id': customOption.getData()[ curIndex ].id,
      'menuName': '子菜单名称'
    } );
    delete childMenu.sub_button;

    customOption.getData()[ curIndex ].sub_button.push( childMenu );

    var addObj = $( getChildMenuHtml() );

    $( this ).before( addObj );
    addObj.trigger( 'click' );
    var appendAfterLength = $( '.js_addMenuBox', $( this ).parent() ).length;
    if ( appendAfterLength > 0 ) {
      $( this ).parent().parent().parent().addClass( 'haschild_menu' );
    }
    if ( appendAfterLength >= 5 ) {
      $( this ).hide();
    }

    var curParentObj = customOption.getData()[ curIndex ];
    curParentObj.url = '';
    curParentObj.type = null;
    curParentObj.value = '';
    curParentObj.news_info = null;

  }
  // 添加确认
  $( '#addChildSure' ).on( 'click', function() {
    doAddChildMenu.call( $( this ).parents( '#addChildConfirm' ).modal( 'hide' ).data( 'menuEvent' ) );
  } );

  // 消息类型切换
  $( '.js_tab_navs .tab_nav' ).click( function() {
    var editIndex = $( this ).attr( 'edit-index' );
    $( this ).addClass( 'selected' ).siblings().removeClass( 'selected' );
    var currentTab = $( '.tab_panel .tab_content', $( this ).parents( '.msg_tab' ) ).eq( editIndex ).fadeIn();
    currentTab.siblings().hide();
    if ( $( '.wait_content', currentTab ).length && !$( '.wait_content', currentTab ).html() ) {
      $( '.tab_cont_cover', currentTab ).show();
    }
  } );

  $( '[name="msg_type"]', '.frm_vertical_pt' ).change( function() {
    removeCheckError();
    if ( $( this ).attr( 'data-editing' ) === '1' ) {
      $( '#edit' ).hide();
      $( '#url' ).fadeIn();
    } else {
      $( '#edit' ).fadeIn();
      $( '#url' ).hide();
    }
  } );

  returnParam.tabChange = function() {
    customMenuMaterialCallback();
    if ( appid ) {
      if ( !clickLoad ) {
        clickLoad = !0;
        $( '#menu_manage' ).show();
        $( '#js_none' ).show();
        menuAjaxDataRequest( appid, function( data ) {

        } );
      }
    } else {
      $( '#menu_manage' ).hide();
    }
  }



  // 父菜单的标签
  function getParentMenuHtml() {

    var html = '';
    html += '<li class="pre_menu_item menu_item js_itemchange">';
    html += '<div class="sub_pre_menu_box">';
    html += '<ul class="sub_pre_menu_list">';
    html += '<li class="add_childMenu_css js_doAddMenuBox">';
    html += '<span class="menuName_css jsSubView js_addL2Btn iconfont icon-jiahao" title="最多添加5个子菜单" draggable="false"></span>';
    html += '</li>';
    html += '</ul>';
    html += '<i class="arrow arrow_out"></i>';
    html += '<i class="arrow arrow_in"></i>';
    html += '</div>';
    html += '<span class="menuName_css parent_menu">';
    html += '<span class="iconfont icon-menus js_hasChild"></span>';
    html += '<span class="iconfont icon-sort"></span>';
    html += '<span class="parent_menu_name">菜单名称</span>';
    html += '</span>';
    html += '</li>';

    return html;
  }

  // 子菜单的标签
  function getChildMenuHtml() {

    var html = '';

    html += '<li class="childMenu_item js_addMenuBox">';
    html += '<span class="menuName_css jsSubView js_addL2Btn">';
    html += '<span class="iconfont icon-sort"></span><span class="child_menuName">子菜单名称</span>';
    html += '</span>';
    html += '</li>';

    return html;
  }
  // 停用菜单按钮
  $( '.disable_menu' ).click( function() {
    $.ajax( {
      type: 'post',
      url: '/CustomMenu/close_menu',
      data: {
        app_id: appid
      },
      success: function( data ) {
        console.log( data );
        var data = typeof data === 'string' ? $.parseJSON( data ) : data;
        if ( data.ret == 0 ) {
          $( '.menu_form_area,.edit_menu > button,.sort_btn_wrp' ).addClass( 'hide' );
          $( '.mobile_backdrop' ).removeClass( 'hide' ).addClass( 'in' );
          $( '.enable_menu' ).removeClass( 'hide' );
          ShowTitleMessage.show( '已停用菜单！', showTime );
        } else {
          ShowTitleMessage.showWarning( data.msg, showTime );
        }
      }
    } )
  } )


  return returnParam;
} );
